<?php

include_once("$config[webroot]/includes/page_utf_class.php");
include_once($config['webroot']."/module/activity_common/includes/plugin_activity_class.php");

$activity=new ActivityCommon();

if($_GET['operation']=="add" or $_GET['operation']=="edit")
{
    if($_POST['act'])
    {
        unset($_GET['s']);
        unset($_GET['m']);
        unset($_GET['operation']);
        //添加活动
        $_POST['stime'].=(' '.$_POST['startHour'].':'.$_POST['startMinute'].':00');
        $_POST['etime'].=(' '.$_POST['endHour'].':'.$_POST['endMinute'].':00');
        if($_POST['type']){
            $_POST['type_config']=$_POST['type_config_'.$_POST['type']];
        }else{
            $_POST['type_config']='';
        }
        if(is_array($_POST['type_config'])){
            $_POST['type_config']=implode('-', $_POST['type_config']);
        }

        $_POST['tags']=@implode(',',$_POST['tags']);
        if($_POST["act"]=='save')
        {
            $activity->add_activity();
        }
        //修改活动
        if($_POST["act"]=='edit' and is_numeric($_POST['id']))
        {
            $activity->edit_activity();
            unset($_GET['editid']);
        }
        $getstr=implode('&',convert($_GET));
        msg("?m=activity_common&s=activity.php&$getstr");
    }
    //活动信息
    if($_GET['editid'] and is_numeric($_GET['editid']))
    {
        $sql="select * from ".ACTIVITY_COMMON." where id='$_GET[editid]'";
        $db->query($sql);
        $de=$db->fetchRow();
        $de['type_config_'.$de['type']]=explode('-', $de['type_config']);

        $de['tags'] =$de['tags']?@explode(',',$de['tags']):array();


        if($de['type']==3)
        {
            $sql="SELECT id,pic,pname,price,market_price,cost_price,sku as code,stock as amount FROM ".SETMEAL." where id in(".trim($de['type_config_'.$de['type']][1],',').") and statu>-3 order by id desc";
            $db->query($sql);
            $de['products']=$db->getRows();
        }

        //品牌名
        $de['brandname'] = '';

        if(!empty($de['brand_ids'])){
            $sql="select GROUP_CONCAT(`name`) AS name from ".BRAND." where id IN($de[brand_ids])";
            $db->query($sql);
            $brandName = $db->fetchRow();
            $de['brandname'] = $brandName['name'];
        }
    }
}

else if ($_GET['operation']=="getbrand"){
    function get_brand($catid,$sbrand=NULL)
    {
        global $db;
        //------------------------------------------------------------

        $id[0]=substr($catid, 0,4);
        $id[1]=substr($catid, 0,6);
        $id[1]=$catid;

        if(!empty($id[2]))
            $db->query("SELECT brand FROM ".PCAT." WHERE catid='$id[2]'");
        $brand=$db->fetchField('brand');

        if(empty($brand)&&!empty($id[1]))
        {
            $db->query("SELECT brand FROM ".PCAT." WHERE catid='".$id[1]."'");
            $brand=$db->fetchField('brand');
        }
        if(empty($brand)&&!empty($id[0]))
        {
            $db->query("SELECT brand FROM ".PCAT." WHERE catid='".$id[0]."'");
            $brand=$db->fetchField('brand');
        }
        if((!empty($brand))||$catid==0)
        {
            if($catid==0){
                $sql="select * from ".BRAND." where 1 order by displayorder asc ";


            }else{

                $sql="select * from ".BRAND." where id in ($brand) order by displayorder asc ";
            }
            $db->query($sql);
            $re=$db->getRows();
            $op=NULL;
            foreach($re as $v)
            {
                if($v['id']==$sbrand)
                    $s='selected="selected"';
                else
                    $s=NULL;
                $op.='<option '.$s.' value="'.$v["id"].'">'.$v["name"].'</option>';
            }
            return $op;
        }
        else
            return '';
    }

    //根据品牌名搜索品牌
    function get_brand_new($brandName,$limit=10){
        global $db;
        if($brandName==''){
            $db->query("SELECT id,name FROM ".BRAND." ORDER BY create_time DESC LIMIT ".$limit);
        }else{
            $db->query("SELECT id,name FROM ".BRAND." WHERE name LIKE '%".mysql_escape_string($brandName)."%' ORDER BY create_time DESC");
        }
        $brandInfo = $db->getRows();
        $op = "";
        foreach($brandInfo as $v)
        {
            $op.='<li style="cursor:pointer;" bid="'.$v["id"].'">'.$v["name"].'</li>';
        }
        return $op;
    }

// 		echo get_brand($_GET['catid'],$_GET['sbrand']);
    echo get_brand_new($_GET['brandname']);
    exit;
}
else
{
    //删除活动
    if($_GET['delid'])
    {
        $sql="select b.product_id from ".ACTIVITY_COMMON." as a left join ".ACTIVITYPRODUCT." as b on a.id=b.activity_id where a.id='$_GET[delid]'";
        $db->query($sql);
        $s_productid=$db->getRows();

        $sql="delete from ".ACTIVITY_COMMON."  where id='$_GET[delid]'";
        $db->query($sql);
        $sql="delete from ".ACTIVITYPRODUCT."  where activity_id='$_GET[delid]'";
        $db->query($sql);
        unset($_GET['delid']);
        $getstr=implode('&',convert($_GET));
        msg("?m=activity_common&s=activity.php&$getstr");
    }
    if($_POST['act']=='op')
    {
        if(is_array($_POST['chk']))
        {
            $id=implode(",",$_POST['chk']);
            $sql="delete from ".ACTIVITY_COMMON." where id in ($id)";
            $db->query($sql);
            $sql="delete from ".ACTIVITYPRODUCT." where activity_id in ($id)";
            $db->query($sql);
// 				foreach($_POST['chk'] as $list)
// 				{
// 					$db->query("update ".PRO." set promotion_id=0 where promotion_id='$list'");
// 				}
        }
        if($_POST['displayorder'])
        {
            foreach($_POST['displayorder'] as $key=>$list)
            {
                $db->query("update ".ACTIVITY_COMMON." set displayorder='$list' where id='$key'");
            }
        }
        msg("?m=activity_common&s=activity.php");
    }
    //获取活动
    $where = "";
    if($_GET['activity_id']){
        $where .=" and id='$_GET[activity_id]'";
    }
    if($_GET['cat']){
        $where .=" and catid='$_GET[cat]'";
    }
    if($_GET['brandid'] && $_GET['brand']){
        $where .=" and brandid='$_GET[brandid]'";
    }
    if($_GET['tags']){
        $where .=" and (tags like '$_GET[tags]%' or tags like '%,$_GET[tags]%') ";
    }
    if(($_GET['statu']!="") && ($_GET['statu']>=0)){
        $where .=" and status='$_GET[statu]'";
    }
    if($_GET['sdate']!='' && $_GET['edate']!='' && (strtotime($_GET['sdate'])<=strtotime($_GET['edate']))){
        $where .=" and start_time>='".strtotime($_GET['sdate'])."' and end_time<='".(strtotime($_GET['edate'])+86399)."'";
    }else{
        if($_GET['sdate']!='' && $_GET['edate']==''){
            $where .=" and start_time>='".strtotime($_GET['sdate'])."'";
        }
        if($_GET['sdate']=='' && $_GET['edate']!=''){
            $where .=" and end_time<='".(strtotime($_GET['edate'])+86399)."'";
        }
    }
    if($_GET['is_start']!=''){
        $now_time = time();
        switch ($_GET['is_start']){
            case -1:
                $where .= " and end_time<'".$now_time."'";break;
            case 1:
                $where .= " and start_time<='".$now_time."' and end_time>='".$now_time."'";break;
            case 2:
                $where .= " and start_time>'".$now_time."'";break;
            default:
                break;
        }
    }

    $sql="select * from ".ACTIVITY_COMMON." where 1".$where." order by displayorder asc,id desc";
    $page = new Page;
    $page->listRows=20;
    //分页
    if (!$page->__get('totalRows'))
    {
        $db->query($sql);
        $page->totalRows = $db->num_rows();
    }
    $sql .= "  limit ".$page->firstRow.",".$page->listRows;
    $db->query($sql);
    $de['list']=$db->getRows();
    if($de['list'])
    {
        foreach($de['list'] as $key=>$v)
        {
            if ($v['catid']==-1){
                //获取活动下产品总数
                $sql="select * from ".ACTIVITYPRODUCT." where activity_id='$v[id]' ";
                $db->query($sql);
                $de['list'][$key]['num']=$db->num_rows();

            }elseif($v['catid']!=0){
                $tmp=array();
                if ($v['catid']){
                    $sql = "select cat from ".PCAT." where '$v[catid]' like concat(`catid`,'%')  order by catid asc";
                    $db->query($sql);
                    foreach ($cat=$db->getRows() as $item){
                        $tmp[]=$item['cat'];
                    }
                }
                $de['list'][$key]['cat']=implode('->', $tmp);
            }

            if ($v['brand_ids']){
                $sql="select GROUP_CONCAT(`name`) AS name from ".BRAND." where id IN($v[brand_ids])";
                $db->query($sql);
                $brandName = $db->fetchRow();

                $de['list'][$key]['brand']= $brandName['name'];
            }

            if($v['tags']){
                $tmp=array();
                $sql = "select tags from ".TAG." where id  in ($v[tags])";
                $db->query($sql);
                foreach ($tags=$db->getRows() as $item){
                    $tmp[]=$item['tags'];
                }

                $de['list'][$key]['tags']=@implode(',', $tmp);
            }
        }
    }

    $de['page']=$page->prompt();
}
//分类
$sql="select * from ".PCAT." where catid<9999 order by displayorder,catid";
$db->query($sql);
$de['cat']=$db->getRows();
foreach($de['cat'] as $key=>$val)
{
    $sql="select * from ".PCAT." where catid < '".$val['catid']."99' and catid > '".$val['catid']."00' order by displayorder,catid";
    $db->query($sql);
    $a=$db->getRows();
    foreach($a as $ke=>$va)
    {
        $sql="select * from ".PCAT." where catid < '".$va['catid']."99' and catid > '".$va['catid']."00' order by displayorder,catid";
        $db->query($sql);
        $a[$ke]['scat']=$db->getRows();
    }
    $de['cat'][$key]['scat']=$a;
}

//所有标签
include_once("$config[webroot]/module/product/includes/plugin_pro_class.php");
//================================================================
$pro=new pro();
$de['all_tags']=$pro->get_tags();
if ($_GET['tags']){
    $de['tags']=array($_GET['tags']);
}
$condTemp = $_GET;
unset($condTemp['m']);
unset($condTemp['s']);
$cond = "";
if(count($condTemp)){
    $cond = "&".http_build_query($condTemp);
}
$tpl->assign("cond",$cond);
$tpl->assign("de",$de);
$tpl->assign("config",$config);
$tpl->display("activity.htm");

?>